package com.njworkorder.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njworkorder.DTO.AOAddDto;
import com.njworkorder.Entity.AdministrativeOrganization;
import com.njworkorder.Service.AdministrativeOrganizationService;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import com.njworkorder.VO.AoLevelVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Tag(name = "行政组织接口", description = "行政组织相关接口")
@RestController
@RequestMapping("/ao")
public class AOController {

    private final AdministrativeOrganizationService aoService;
    public AOController(AdministrativeOrganizationService aoService) {
        this.aoService = aoService;
    }

    @Operation(summary = "获取行政组织列表")
    @GetMapping("/getList")
    public Result<Page<AdministrativeOrganization>> getList(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize) {
        LambdaQueryWrapper<AdministrativeOrganization> queryWrapper = Wrappers.lambdaQuery();

        queryWrapper.eq(AdministrativeOrganization::getStatus, 2);
        queryWrapper.orderByDesc(AdministrativeOrganization::getPublishTime);

        Page<AdministrativeOrganization> page = aoService.page(new Page<>(pageIndex, pageSize), queryWrapper);

        return ResultUtil.success(page);
    }

    @Operation(summary = "行政组织信息添加")
    @PostMapping("/addInfo")
    public Result<String> addInfo(@RequestBody AOAddDto aoDto, @RequestHeader("Create-Ap-Id") String createApId) {

        LambdaQueryWrapper<AdministrativeOrganization> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AdministrativeOrganization::getName, aoDto.getName());
        long count = aoService.count(queryWrapper);
        if (count > 0) {
            return ResultUtil.fail("组织名称已存在!");
        }

        AdministrativeOrganization ao = new AdministrativeOrganization();
        BeanUtils.copyProperties(aoDto, ao);
        String id = UUID.randomUUID().toString().replace("-", "");
        Date now = new Date();
        ao.setId(id);
        ao.setXzzzid(id);
        ao.setModTime(now);
        ao.setCreateApId(createApId);

        boolean save = aoService.save(ao);
        if (save) {
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }

    @Operation(summary = "根据行政组织id删除")
    @GetMapping("/deleteById")
    public Result<String> deleteById(@RequestParam("id") String id) {
        boolean remove = aoService.removeById(id);
        if (remove) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.fail("删除失败");
    }

    @Parameters({
            @Parameter(name = "oCode", description = "行政组织编码", required = true),
            @Parameter(name = "shortNameExt", description = "简称", required = true),
            @Parameter(name = "status", description = "数据状态", example = "2为正常状态,6为冻结状态,8为失效状态", required = true)
    })
    @Operation(summary = "根据行政组织id更新数据")
    @GetMapping("/updateInfo")
    public Result<String> updateInfo(@RequestParam("id") String id, @RequestParam("oCode") String oCode, @RequestParam("shortNameExt") String shortNameExt, @RequestParam("status") String status) {

        LambdaUpdateWrapper<AdministrativeOrganization> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdministrativeOrganization::getId, id);
        updateWrapper.set(AdministrativeOrganization::getModTime, new Date());
        updateWrapper.set(AdministrativeOrganization::getOCode, oCode);
        updateWrapper.set(AdministrativeOrganization::getShortNameExt, shortNameExt);
        updateWrapper.set(AdministrativeOrganization::getStatus, status);

        boolean update = aoService.update(updateWrapper);
        if (update) {
            return ResultUtil.success("更新成功");
        }
        return ResultUtil.fail("更新失败");
    }

    @Operation(summary = "根据id查询行政组织信息")
    @GetMapping("/getById")
    public Result<AdministrativeOrganization> getById(@RequestParam("id") String id) {
        AdministrativeOrganization ao = aoService.getById(id);
        return ResultUtil.success(ao);
    }

    @Operation(summary = "组织架构树状图")
    @GetMapping("/getContents")
    public Result<List<AoLevelVo>> getContents() {

        LambdaQueryWrapper<AdministrativeOrganization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdministrativeOrganization::getId, AdministrativeOrganization::getXzzzid, AdministrativeOrganization::getName, AdministrativeOrganization::getParentId, AdministrativeOrganization::getShortNameExt);
        queryWrapper.apply("1=1");
        List<AdministrativeOrganization> list = aoService.list(queryWrapper);

        List<AdministrativeOrganization> listF = list.stream().filter(item -> item.getParentId().isEmpty() || item.getParentId().isBlank()).toList();
        List<AoLevelVo> listLevelVo = new ArrayList<>();
        AoLevelVo aoLevelVo;
        for (AdministrativeOrganization item : listF) {
            aoLevelVo = new AoLevelVo();
            BeanUtils.copyProperties(item, aoLevelVo);
            aoLevelVo.setGrade(1);
            aoLevelVo.setChildren(getAllAoLevel(item.getXzzzid(), list, 2));
            listLevelVo.add(aoLevelVo);
        }
        return ResultUtil.success(listLevelVo);
    }

    public List<AoLevelVo> getAllAoLevel(String id, List<AdministrativeOrganization> list, int grade) {
        List<AdministrativeOrganization> list1 = list.stream().filter(item -> item.getParentId().equals(id)).toList();
        List<AoLevelVo> listLevelVo = new ArrayList<>();
        AoLevelVo aoLevelVo;
        for (AdministrativeOrganization item : list1) {
            aoLevelVo = new AoLevelVo();
            BeanUtils.copyProperties(item, aoLevelVo);
            aoLevelVo.setGrade(grade);
            aoLevelVo.setChildren(getAllAoLevel(item.getXzzzid(), list, grade + 1));
            listLevelVo.add(aoLevelVo);
        }
        return listLevelVo;
    }


}